<template>
	<view>
		<map
			id="map"
			scale="15"
			:longitude="longitude"
			:latitude="latitude"
			:enable-poi="true"
			class="map"
			:style="mapStyle"
			:polyline="polyline"
			:markers="markers"
			@longpress="showHandle"
		>
			<!-- <cover-image class="location" src="../static/workbench/location.png" @tap="returnLocationHandle()" /> -->
			<cover-view style="width: 100px;position: absolute;bottom: 180px;right: 25px;">
				<button v-if="true" @tap="moniDriving">模拟行程</button>
			</cover-view>
			<cover-view class="information-container" v-show="infoStatus">
				<cover-image src="../static/move/close-icon.png" class="close-icon" @tap="hideHandle"></cover-image>
				<cover-view class="info">
					<cover-view class="label">剩余</cover-view>
					<cover-view class="value">{{ distance }}公里</cover-view>
					<cover-view class="label">，预计</cover-view>
					<cover-view class="value">{{ duration }}分钟</cover-view>
				</cover-view>
			</cover-view>
		</map>
	</view>
</template>

<script>
let QQMapWX = require('../../lib/qqmap-wx-jssdk.min.js');
let qqmapsdk;
export default {
	data() {
		return {
			moniPoints:[],
			moniInterval: null,
			moni: false,
			map: null,
			mapStyle: '',
			startLatitude: 0,
			startLongitude: 0,
			endLatitude: 0,
			endLongitude: 0,
			latitude: 0,
			longitude: 0,
			targetLatitude: undefined,
			targetLongitude: undefined,
			distance: 0,
			duration: 0,
			polyline: [],
			markers: [],
			timer: null,
			infoStatus: true
		};
	},
	methods: {
		returnLocationHandle: function() {
			let that = this;
			wx.getLocation({
				type: 'wgs84',
				success (res) {
					that.latitude = res.latitude;
					that.longitude = res.longitude;
					console.log("获取定位成功:" + that.latitude + " " + that.longitude)
					wx.getSystemInfo({
						success: (res) => {
							console.log('SystemInfo:', res.platform);
							if(res.platform != 'android' && res.platform != 'ios') {
								//解决电脑端不更新定位演示问题
								let location = { latitude: 24.626664, longitude: 118.074079 };
								uni.$emit('updateLocation', location);
							}
						}
					});
				}
			})
			this.map.moveToLocation();
		},
		//模拟司机驾驶
		moniDriving: function(){
			let that = this;
			that.moni = !that.moni;
			let from = {latitude: that.latitude, longitude: that.longitude}
			let to = {latitude: that.targetLatitude, longitude: that.targetLongitude}
			if(that.moni) {
				console.log("开始模拟");
				that.moniInterval = setTimeout(function(){
					that.latitude = that.moniPoints[0].latitude;
					that.longitude = that.moniPoints[0].longitude;
					for(let i=1;i<that.moniPoints.length;i++){
						let a = that.moniPoints[i-1].latitude - that.moniPoints[i].latitude;
						let b = that.moniPoints[i-1].longitude - that.moniPoints[i].longitude;
						
						let durationTime = Math.floor(Math.sqrt (a * a + b * b)*1500000);
						that.map.translateMarker({
							markerId: 1,
							destination: {
								latitude: that.moniPoints[i].latitude,
								longitude: that.moniPoints[i].longitude
							},
							autoRotate: true,
							moveWithRotate: true,
							rotate: 0,
							success:function(){
								that.latitude = that.moniPoints[i].latitude;
								that.longitude = that.moniPoints[i].longitude;
								let data = {
									orderId: that.orderId,
									latitude: that.latitude,
									longitude: that.longitude
								};
								uni.request({
									url: that.url.updateOrderLocationCache,
									method: 'POST',
									header: {
										token: uni.getStorageSync('token')
									},
									data: data,
									success: function(resp) {},
									fail: function(error) {}
								});
							},
							duration: durationTime
						});
					}
				},1)
			} else {
				console.log("停止模拟");
				clearTimeout(that.moniInterval)
				that.moniTimer = null;
				clearInterval(that.timer);
			}
			
		},
		hideHandle: function() {
		    this.infoStatus = false;
		},
		showHandle: function() {
		    this.infoStatus = true;
		},
		formatPolyline(polyline) {
		    let coors = polyline;
		    let pl = [];
		    //坐标解压（返回的点串坐标，通过前向差分进行压缩）
		    const kr = 1000000;
		    for (let i = 2; i < coors.length; i++) {
		        coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
		    }
		    //将解压后的坐标放入点串数组pl中
		    for (let i = 0; i < coors.length; i += 2) {
		        pl.push({
		            longitude: coors[i + 1],
		            latitude: coors[i]
		        });
		    }

		    return pl;
		},
		calculateLine: function() {
			let ref = this;
		    //如果还没有获得最新的定位，就不计算最佳线路
		    if (ref.latitude == 0 || ref.longitude == 0) {
		        return;
		    }
		    qqmapsdk.direction({
		        mode: ref.mode, //可选值：'driving'（驾车）、'walking'（步行）、'bicycling'（骑行），不填默认：'driving',可不填
		        //from参数不填默认当前地址
		        from: {
		            latitude: ref.latitude,
		            longitude: ref.longitude
		        },
		        to: {
		            latitude: ref.targetLatitude,
		            longitude: ref.targetLongitude
		        },
		        success: function(resp) {
		            let route = resp.result.routes[0];
		            let distance = route.distance;
		            let duration = route.duration;
		            let polyline = route.polyline;
		            ref.distance = Math.ceil((distance / 1000) * 10) / 10;
		            ref.duration = duration;
		
		            let points = ref.formatPolyline(polyline);
					ref.moniPoints = points;
		            ref.polyline = [
		                {
		                    points: points,
		                    width: 6,
		                    color: '#05B473',
		                    arrowLine: true
		                }
		            ];
					ref.markers = [
						{
							id: 1,
							latitude: ref.latitude,
							longitude: ref.longitude,
							width: 35,
							height: 35,
							anchor: {
								x: 0.5,
								y: 0.5
							},
							iconPath: '../static/move/car.png'
						}
					];
		        },
		        fail: function(error) {
		            console.log(error);
		        }
		    });
		}
	},
	onLoad: function(options) {
		let that = this;
		that.orderId = options.orderId;
		qqmapsdk = new QQMapWX({
			key: that.tencent.map.key
		});
		//初始化地图
		that.map = uni.createMapContext('map');
		let windowHeight = uni.getSystemInfoSync().windowHeight;
		that.mapStyle = `height:${windowHeight}px`;
		that.returnLocationHandle();
	},
	onShow: function() {
		let that = this;

		//实时获取定位
		uni.$on('updateLocation', function(location) {
			if (location != null && !that.moni) {
				that.latitude = location.latitude;
				that.longitude = location.longitude;
			}
		});
		wx.getSystemInfo({
			success: (res) => {
				console.log('SystemInfo:', res.platform);
				if(res.platform != 'android' && res.platform != 'ios') {
					//解决电脑端不更新定位演示问题
					let location = { latitude: 24.62714, longitude: 118.08934 };
					uni.$emit('updateLocation', location);
				}
			}
		});
		let data = {
			orderId: that.orderId
		};
		
		that.ajax(that.url.searchOrderForMoveById, 'POST', data, function(resp) {
			let result = resp.data.result;
			console.log(result);
			let startPlaceLocation = JSON.parse(result.startPlaceLocation);
			that.startLatitude = startPlaceLocation.latitude;
			that.startLongitude = startPlaceLocation.longitude;
		
			let endPlaceLocation = JSON.parse(result.endPlaceLocation);
			that.endLatitude = endPlaceLocation.latitude;
			that.endLongitude = endPlaceLocation.longitude;
		
			let status = result.status;
			if (status == 2) {
				//定位到上车点
				that.targetLatitude = that.startLatitude;
				that.targetLongitude = that.startLongitude;
				that.mode = 'driving';
			} else if (status == 3 || status == 4) {
				//定位到终点
				that.targetLatitude = that.endLatitude;
				that.targetLongitude = that.endLongitude;
				that.mode = 'driving';
			}
			that.calculateLine(that);
			that.timer = setInterval(function() {
				that.calculateLine(that);
			}, 6000);
		});
	},
	onHide: function() {
		let that=this
		uni.$off('updateLocation');
		clearInterval(that.timer)
		that.timer = null
	}
};
</script>

<style lang="less">
@import url('move.less');
</style>
